<?php

namespace App\Services;

use App\Exceptions\AppException;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use TencentCloud\Captcha\V20190722\CaptchaClient;
use TencentCloud\Captcha\V20190722\Models\DescribeCaptchaResultRequest;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;

class UserService
{

    /**
     * 腾讯云验证码校验
     * @param string $ticket
     * @param string $randstr
     * @param string $userIp
     * @throws AppException
     */
    public function checkTencentCaptcha(string $ticket, string $randstr, string $userIp)
    {
        $cred = new Credential(config('blog.tencent_secret_id'), config('blog.tencent_secret_key'));
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("captcha.tencentcloudapi.com");

        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new CaptchaClient($cred, "", $clientProfile);

        $req = new DescribeCaptchaResultRequest();

        $params = [
            'CaptchaType'  => 9,
            'Ticket'       => $ticket,
            'UserIp'       => $userIp,
            'Randstr'      => $randstr,
            'CaptchaAppId' => config('blog.tencent_captcha_id'),
            'AppSecretKey' => config('blog.tencent_captcha_key'),
        ];

        $req->fromJsonString(json_encode($params));

        $resp = $client->DescribeCaptchaResult($req);

        //等于1为验证通过
        if ($resp->getCaptchaCode() !== 1) {
            throw new AppException($resp->getCaptchaMsg());
        }
    }

    /**
     * 登录校验
     * @param string $username
     * @param string $password
     * @return User
     * @throws AppException
     */
    public function login(string $username, string $password)
    {
        $user = User::where('username', $username)->first();
        if (!$user) {
            throw new AppException('用户名或密码错误');
        }

        if (Hash::check($password, $user->password) == false) {
            throw new AppException('用户名或密码错误');
        }

        return $user;
    }

    /**
     * 修改登录密码
     * @param User $user
     * @param string $passwordOld
     * @param string $passwordNew
     * @throws AppException
     */
    public function changePassword(User $user, string $passwordOld, string $passwordNew)
    {
        if (Hash::check($passwordOld, $user->password) == false) {
            throw new AppException('旧密码不正确');
        }

        if ($passwordNew == $passwordOld) {
            throw new AppException('新密码不能与旧密码相同');
        }

        $user->password = Hash::make($passwordNew);
        $user->save();
    }

}
